#coding=utf-8

'''
requires Python 3.6 or later
pip install requests
'''
import base64
import json
import uuid
import requests
import json
from config import *
from pydub import AudioSegment
import os
import torch
import soundfile as sf
from diffusers import StableAudioPipeline
import os
from huggingface_hub import login

# 方法一：直接在代码中提供令牌（不推荐）
# 请确保不将令牌硬编码在代码中，避免泄露风险。
token = hf_api
login(token=token)

# os.environ["HF_ENDPOINT"] = "https://hf-mirror.com"
pipe = StableAudioPipeline.from_pretrained("stabilityai/stable-audio-open-1.0", torch_dtype=torch.float16)
pipe = pipe.to("cuda")

negative_prompt = "Low quality."

# set the seed for generator
generator = torch.Generator("cuda").manual_seed(0)
def get_env_sound(id_file,text):
    # run the generati:on
    audio = pipe(
        text,
        negative_prompt=negative_prompt,
        num_inference_steps=10,
        audio_end_in_s=6,
        num_waveforms_per_prompt=3,
        generator=generator,
    ).audios

    output = audio[0].T.float().cpu().numpy()
    sf.write(f"{id_file}.mp3", output, pipe.vae.sampling_rate)
def merge_mp3_files(input_folder, output_file):
    # 获取所有文件并排序
    files = sorted([f for f in os.listdir(input_folder) if f.endswith('.mp3')], key=lambda x: int(os.path.splitext(x)[0]))
    
    # 初始化一个空的音频
    combined = AudioSegment.empty()
    
    for file in files:
        filepath = os.path.join(input_folder, file)
        print(f"正在合成：{filepath}")
        audio = AudioSegment.from_mp3(filepath)
        combined += audio
    
    # 导出合成后的文件
    combined.export(output_file, format="mp3")
    print(f"合成完成，文件保存为：{output_file}")
def get_voice(id_file,char,text):
    # 填写平台申请的appid, access_token以及cluster
    appid = "2468360731"
    access_token= huoshan_zpi
    cluster = "volcano_tts"

    voice_type = char
    host = "openspeech.bytedance.com"
    api_url = f"https://{host}/api/v1/tts"

    header = {"Authorization": f"Bearer;{access_token}"}

    request_json = {
        "app": {
            "appid": appid,
            "token": access_token,
            "cluster": cluster
        },
        "user": {
            "uid": "388808087185088"
        },
        "audio": {
            "voice_type": voice_type,
            "encoding": "mp3",
            "speed_ratio": 1.0,
            "volume_ratio": 1.0,
            "pitch_ratio": 1.0,
        },
        "request": {
            "reqid": str(uuid.uuid4()),
            "text": text,
            "text_type": "plain",
            "operation": "query",
            "with_frontend": 1,
            "frontend_type": "unitTson"

        }
    }

    try:
        resp = requests.post(api_url, json.dumps(request_json), headers=header)
        # print(f"resp body: \n{resp.json()}")
        if "data" in resp.json():
            data = resp.json()["data"]
            file_to_save = open(f"{id_file}.mp3", "wb")
            file_to_save.write(base64.b64decode(data))
    except Exception as e:
        e.with_traceback()


if __name__ == '__main__':
    root_dir = os.getcwd()
    input_juben = os.path.join(root_dir,"/output/绑定内娱嫂子系统后_第七章.json")
    mp3_dir = os.path.join(root_dir,"绑定内娱嫂子系统后_第七章")
    merged_mp3 = os.path.join(root_dir,"绑定内娱嫂子系统后_第七章.mp3")
    if not os.path.exists(mp3_dir):
        os.makedirs(mp3_dir,exist_ok=True)
    with open(input_juben,encoding='utf-8') as reader:
        juben = json.load(reader)
    for key,value in juben.items():
        if value["type"]=="人声":
            get_voice(os.path.join(mp3_dir,key),value["info"]["voice_type"],value["info"]["content"])
        if value["type"]=="环境声":
            get_env_sound(os.path.join(mp3_dir,key),value["info"])
    merge_mp3_files(mp3_dir,merged_mp3)
            
